import { defineStore } from "pinia"
import API from '@/api/index'
import { getQuery } from '@/lib/js/utils'

const useStore = defineStore({
  id: "user",
  persist: {
    enabled: true,
    key: 'LP_USER'
  },
  state: () => ({
    user: null,
    sessionId: '',
  }),
  actions: {
    setSessionId(data) {
      this.sessionId = data
    },
    set(data) {
      this.user = data
    },
    clear() {
      this.set(null)
      this.setSessionId('')
    },
    async logout() {
      this.set(null)
      let res = await API.loginOut({ sessionId: this.sessionId })
      this.setSessionId('')
      let { code, data, msg } = res.data
      console.log('logout success', res)
      location.href = data.jumpUrl
    },
    async getUser() {
      const router = useRouter()

      const { sessionId } = getQuery()

      let res = await API.getuserinfo({ sessionId })
      let { code, data, msg } = res.data

      console.log(11, sessionId, { code, data, msg })
      // return

      // code = 0
      // data = { username: 'Peicheng Liu', id: 222 }
      if (code == -1) {
        location.href = data.jumpUrl
      } else {
        this.set(data)
        this.setSessionId(sessionId)
        router.replace({ path: '/index' })
      }
    }
  }
})

export default useStore